#!/bin/bash
mkdir -p ./log
# 1- lib, 2-bench
curpath=`pwd`
# 注意nice不能sudo
NICE=""

#"sudo nice -10" 
# AARCH64_PLATFORM=`uname -a | grep "aarch64"`
# PERF=
# if [ ! -n "$AARCH64_PLATFORM" ] ; then
# 	PERF="perf stat -e cache-misses --no-big-num -o ./log/perf_test.txt"
# fi

do_bench() {
	# $1 libpath
	# $2 benchpath
	echo "LD_PRELOAD=$1 $2"
	${NICE} ${PERF} env LD_PRELOAD=$1 $2 2> ./log/tmp.tsv
# 	pcache_misses=""
# 	ecache_misses=""
# if [ ! -n "$AARCH64_PLATFORM" ] ; then
# 	pcache_misses=`cat ./log/perf_test.txt | grep "cache-misses:u" | grep " [0-9]\+" -o | head -n1`
# 	ecache_misses=`cat ./log/perf_test.txt | grep "cache-misses:u" | grep " [0-9]\+" -o | tail -n1`
# fi
	cat ./log/tmp.tsv
	cat ./log/tmp.tsv | while read line
	do
		echo "$3 ${line}${pcache_misses}${ecache_misses}" >> $4
	done
	# 确保文件已写入, 防止影响下一次执行
	sleep 1
}

liblist="flat
cacflat
ccsync
cacccsyn
dsmsync
cacdsmsyn
hsync
cachsyn
rcl
ffwd"

# backup 
mv ./log/result.tsv ./log/result_old.tsv

if [ ! -n "$AARCH64_PLATFORM" ] ; then
	echo "lib bench threads result(mop/s) pcache-misses ecache-misses" > ./log/result.tsv
else
	echo "lib bench threads result(mop/s)" > ./log/result.tsv
fi


trap "exit" INT
echo "run ${1} x 2 times (gcc + clang)" 
for ((i=1;i<=${1};i++))
do
	for lib in ${liblist}   
	do
		do_bench ${curpath}/build_lib/glibapfsds_${lib}.so ${curpath}/build/gtest_basic.o ${lib} ./log/result.tsv
		do_bench ${curpath}/build_lib/cllibapfsds_${lib}.so ${curpath}/build/cltest_basic.o ${lib} ./log/result.tsv
	done
done

cd script
python3 geomean.py ../log/result.tsv
